package tech.mhuang.pacebox.springboot.core.permission;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import tech.mhuang.pacebox.core.exception.BusinessException;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.core.permission.annotation.Permission;
import tech.mhuang.pacebox.springboot.core.permission.extra.IPermissionManager;
import tech.mhuang.pacebox.springboot.core.permission.extra.NoLoopPermissionManager;
import tech.mhuang.pacebox.springboot.core.spring.start.SpringContextHolder;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.lang.reflect.Method;

/**
 * 权限拦截
 *
 * @author mhuang
 * @since 2021.0.5.0
 */
public class PermissionInteceptor implements MethodInterceptor {

    /**
     * 未自定义指定的bean则用此类
     */
    private final IPermissionManager commonPermissionManager;

    public PermissionInteceptor(IPermissionManager commonPermissionManager) {
        this.commonPermissionManager = commonPermissionManager;
    }

    @Nullable
    @Override
    public Object invoke(@NotNull MethodInvocation invocation) throws Throwable {
        Method method = invocation.getMethod();
        Permission permission = method.getAnnotation(Permission.class);
        IPermissionManager permissionManager = null;
        if (permission.manager() != NoLoopPermissionManager.class) {
            Class<? extends IPermissionManager> permissionManagerClass = permission.manager();
            permissionManager = permissionManagerClass.getDeclaredConstructor().newInstance();
        }
        if (StringUtil.isNotEmpty(permission.beanName())) {
            permissionManager = SpringContextHolder.getBean(permission.beanName(), IPermissionManager.class);
        }
        if (permissionManager == null) {
            permissionManager = commonPermissionManager;

            if (permissionManager == null) {
                throw new BusinessException(Result.SYS_FAILD, "请配置权限处理器");
            }
        }
        permissionManager.permission(permission);
        return invocation.proceed();
    }
}